package club.weiyuanstudio.android.app.message_station.ui.setting

import android.app.Application
import android.content.Context.MODE_PRIVATE
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import java.util.UUID.randomUUID

class SettingViewModel(application: Application) : AndroidViewModel(application) {
    var settingData = MutableLiveData<SettingData>()

    private val preferences =
        getApplication<Application>().getSharedPreferences("data", MODE_PRIVATE)

    enum class SettingType {
        UUID,
        DEVICE_NAME,
        API_TOKEN,
        FORWARD_NUMBER,
    }

    fun loadSettingDataFromPreferences() {
        val preferences = getApplication<Application>().getSharedPreferences("data", MODE_PRIVATE)

        if (!preferences.contains(SettingType.UUID.name)) {
            val uuid = randomUUID().toString()
            preferences.edit().putString(SettingType.UUID.name, uuid).apply()
        }

        val uuid = preferences.getString(SettingType.UUID.name, "UNSET")!!
        val deviceName = preferences.getString(SettingType.DEVICE_NAME.name, "")!!
        val apiToken = preferences.getString(SettingType.API_TOKEN.name, "")!!

        settingData.postValue(SettingData(uuid, deviceName, apiToken))
    }

    fun setSettingDataToPreferences(settingData: SettingData) {
        preferences.edit().putString(SettingType.DEVICE_NAME.name, settingData.deviceName).apply()
        preferences.edit().putString(SettingType.API_TOKEN.name, settingData.apiToken).apply()
    }

    data class SettingData(var uuid: String, var deviceName: String, var apiToken: String)
}
